package com.lty.jeeg.server.common.config;

import com.lty.jeeg.server.modules.sys.model.JobModel;
import com.lty.jeeg.server.modules.sys.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author LTY
 */
@Configuration
public class JobConfig {

//	private final JobService jobService;
//	private final TaskExecutor taskExecutor;
//
//	@Autowired
//	public JobConfig(JobService jobService, TaskExecutor taskExecutor) {
//		this.jobService = jobService;
//		this.taskExecutor = taskExecutor;
//	}

	public static final String KEY = "applicationContextSchedulerContextKey";

	@Bean("adminQuartzScheduler")
	public SchedulerFactoryBean quartzScheduler(DataSource dataSource) {
		SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
//
//		try {
//			quartzScheduler.setQuartzProperties(
//					PropertiesLoaderUtils.loadProperties(new ClassPathResource("quartz.properties")));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		quartzScheduler.setAutoStartup(true);
		quartzScheduler.setDataSource(dataSource);
		quartzScheduler.setOverwriteExistingJobs(true);
		quartzScheduler.setApplicationContextSchedulerContextKey(KEY);
		quartzScheduler.setStartupDelay(10);

		return quartzScheduler;
	}

//	/**
//	 * 初始化一个定时删除日志的任务
//	 */
//	@PostConstruct
//	public void initDeleteLogsJob() {
//		taskExecutor.execute(() -> {
//			JobModel jobModel = new JobModel();
//			jobModel.setJobName("delete-logs-job");
//			jobModel.setCron("0 0 0 * * ?");
//			jobModel.setDescription("定时删除三个月前日志");
//			jobModel.setSpringBeanName("sysLogServiceImpl");
//			jobModel.setMethodName("deleteLogs");
//			jobModel.setIsSysJob(true);
//			jobModel.setStatus(1);
//
//			jobService.saveJob(jobModel);
//		});
//	}

}
